/**
 * @description 日期组件
 * @author Rid King
 * @since 2018-02-04
*/

import strer from '../../../strer/2.0.0/js/strer'

export default {
  /**
   * @function 格式化时间
   * @param {Number/Date} date // 日期值
   * @param {String} pattern // 格式化字符串
   * @param {Boolean} isAutoDate 是否使用当前时间
   * @return {String}
  */
  format (date, pattern, isAutoDate) {
    // 参数处理
    pattern = pattern || 'yyyy-MM-dd HH:mm:ss'
    if (!(date instanceof Date)) {
      date = parseInt(date, 10)
      if (isNaN(date)) {
        if (!isAutoDate) {
          return ''
        }
        date = new Date()
      }
      else {
        date = new Date(date)
      }
    }
    // 验证date是否正确
    if (!date.getFullYear()) {
      if (!isAutoDate) {
        return ''
      }
      date = new Date()
    }

    let year = date.getFullYear()
    let month = date.getMonth() + 1
    let date2 = date.getDate()
    let day = date.getDay()
    let hours = date.getHours()
    let minutes = date.getMinutes()
    let seconds = date.getSeconds()

    replacer(/yyyy/g, pad(year, 4))
    replacer(/yy/g, pad(year.toString().slice(2), 2))
    replacer(/MM/g, pad(month, 2))
    replacer(/M/g, month)
    replacer(/dd/g, pad(date2, 2))
    replacer(/d/g, date2)
    replacer(/HH/g, pad(hours, 2))
    replacer(/H/g, hours)
    replacer(/hh/g, pad(hours % 12, 2))
    replacer(/h/g, hours % 12)
    replacer(/mm/g, pad(minutes, 2))
    replacer(/m/g, minutes)
    replacer(/ss/g, pad(seconds, 2))
    replacer(/s/g, seconds)
    replacer(/W/g, ['星期天', '星期一', '星期二', '星期三', '星期四', '星期五', '星期六'][day])
    replacer(/w/g, ['Sunday', 'Monday', 'Tuesday', 'Wedesday', 'Thursday', 'Friday', 'Saturday'][day])

    return pattern

    // 格式替换
    function replacer (patternPart, result) {
      pattern = pattern.replace(patternPart, result)
    }

    //对目标字符串的前面补0，使其达到要求的长度
    function pad (source, length) {
      return (source < 0 ? '-' : '') + strer.padLeft(source,length, '0')
    }
  },

  /**
   * @function 格式化时间
   * @param {String} str
   * @return {String}
   */
  formatDiff (str) {
    if (!str) return ''
    var date = new Date(str)
    var time = new Date().getTime() - date.getTime() //现在的时间-传入的时间 = 相差的时间（单位 = 毫秒）
    if (time < 0) {
      return ''
    } else if ((time / 1000 < 30)) {
      return '刚刚'
    } else if (time / 1000 < 60) {
      return parseInt((time / 1000)) + '秒前'
    } else if ((time / 60000) < 60) {
      return parseInt((time / 60000)) + '分钟前'
    } else if ((time / 3600000) < 24) {
      return parseInt(time / 3600000) + '小时前'
    } else if ((time / 86400000) < 31) {
      return parseInt(time / 86400000) + '天前'
    } else if ((time / 2592000000) < 12) {
      return parseInt(time / 2592000000) + '月前'
    } else {
      return parseInt(time / 31536000000) + '年前'
    }
  }
}
